package com.ye.personnel.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ye.personnel.api.department.GwyPullDepartmentListVo;
import com.ye.personnel.api.enums.FlowTypeEnum;
import com.ye.personnel.api.enums.UserTypeEnum;
import com.ye.personnel.api.user.*;
import com.ye.personnel.common.exception.CustomerException;
import com.ye.personnel.common.response.ErrorCode;
import com.ye.personnel.common.utils.HelpUtils;
import com.ye.personnel.common.utils.JwtUtil;
import com.ye.personnel.common.utils.PasswordUtils;
import com.ye.personnel.mapper.dao.GwyAdminUserMapper;
import com.ye.personnel.mapper.dao.GwyDepartmentMapper;
import com.ye.personnel.mapper.entity.GwyAdminUser;
import com.ye.personnel.mapper.entity.GwyDepartment;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Author: yeubo
 * @Date: 2024/1/2 14:26
 */
@Service
@Slf4j
public class CommonService {

    @Autowired
    GwyAdminUserMapper adminUserMapper;
    @Autowired
    GwyDepartmentMapper departmentMapper;
    @Autowired
    GwyCmsSystemService gwyCmsSystemService;

    @Value("${upload.folder}")
    private String uploadFolder;

    @Value("${upload.mapUrl}")
    private String mapUrl;

    public final List<String> contentTypes = Arrays.asList(".jpeg", ".jpg", ".png",".mp4",".xlsx",".xls",".doc",
            ".docx",".gif",".pptx",".ppt",".pdf",".zip",".rar");


    /**
     * 用户登录
     * @param adminLoginDto
     * @return
     */
    public LoginResultVo userLogin(UserLoginDto adminLoginDto){
        String loginName = adminLoginDto.getUserName();
        GwyAdminUser adminUser = adminUserMapper.selectOne(new QueryWrapper<GwyAdminUser>()
                .lambda()
                .eq(GwyAdminUser::getUserName, loginName)
                .last("limit 1"));
        if(adminUser == null){
            throw new CustomerException(ErrorCode.PARAMS_GET_ERROR,"账号不存在");
        }
        if(adminUser.getDisabled() == 1){
            throw new CustomerException(ErrorCode.PARAMS_GET_ERROR,"账号已被禁用");
        }
        boolean checkPwd = PasswordUtils
                .matches(adminUser.getPassword(), adminLoginDto.getTimestamp(), adminLoginDto.getPassword());
        if (!checkPwd) {
            throw new CustomerException(ErrorCode.PARAMS_GET_ERROR, "密码错误");
        }
        //生成令牌
        String token = JwtUtil.createToken(adminUser);
        //更新登录信息
        GwyAdminUser adminUserUpdate = new GwyAdminUser();
        adminUserUpdate.setAdminUserId(adminUser.getAdminUserId());
        adminUserUpdate.setLastLoginTime(new Date());
        adminUserUpdate.setToken(token);
        adminUserMapper.updateById(adminUserUpdate);
        //返回登录信息
        LoginResultVo loginResultVo = BeanUtil.copyProperties(adminUser, LoginResultVo.class);
        GwyDepartment gwyDepartment = departmentMapper.selectById(adminUser.getDepartmentId());
        if(gwyDepartment != null){
            loginResultVo.setDepartmentName(gwyDepartment.getDepartmentName());
            loginResultVo.setDepartmentNo(gwyDepartment.getDepartmentNo());
        }
        loginResultVo.setToken(token);
        return loginResultVo;
    }

    /**
     * 上传文件到本地
     * @param file
     * @return
     */
    public Map<String,String> uploadFileToLocal(MultipartFile file){
        String fileName = file.getOriginalFilename();
        if(Objects.isNull(fileName)){
            throw new CustomerException(ErrorCode.PARAMS_GET_ERROR,"文件资源获取失败");
        }
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        suffixName = StringUtils.lowerCase(suffixName);
        //校验文件类型
        if (!contentTypes.contains(suffixName)) {
            throw new CustomerException(ErrorCode.PARAMS_GET_ERROR,"文件类型不支持");
        }
        fileName = HelpUtils.getRandomStr(6)+ "_" +HelpUtils.getYearMonthDay() + suffixName; // 新文件名
        File dest = new File(uploadFolder + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        String fileSize = HelpUtils.getPrintSize(file.getSize());
        String fileUrl = mapUrl + fileName;
        HashMap<String, String> returnMap = new HashMap<>();
        returnMap.put("fileUrl",fileUrl);
        returnMap.put("filePath",uploadFolder + fileName);
        returnMap.put("fileSize",fileSize);
        return returnMap;
    }

    /**
     * 用户类型列表
     * @return
     */
    public List<UserTypeListVo> userTypeList(){
        UserTypeEnum[] values = UserTypeEnum.values();
        ArrayList<UserTypeListVo> userTypeListVos = new ArrayList<>();
        for (UserTypeEnum typeEnum : values) {
            UserTypeListVo userTypeListVo = new UserTypeListVo();
            userTypeListVo.setUserType(typeEnum.getType());
            userTypeListVo.setUserTypeName(String.valueOf(typeEnum.getName()));
            userTypeListVos.add(userTypeListVo);
        }
        return userTypeListVos;
    }

    /**
     * 发起类型列表
     * @return
     */
    public FlowTypeVo flowTypeList(){
        FlowTypeVo flowTypeVo = new FlowTypeVo();
        FlowTypeEnum[] values = FlowTypeEnum.values();
        List<FlowTypeListVo> flowTypeInList = new ArrayList<>();
        List<FlowTypeListVo> flowTypeManageList = new ArrayList<>();
        List<FlowTypeListVo> flowTypeOutList = new ArrayList<>();
        for (FlowTypeEnum typeEnum : values) {
            Integer flowType = typeEnum.getType();
            FlowTypeListVo flowTypeListVo = new FlowTypeListVo();
            flowTypeListVo.setFlowType(flowType);
            flowTypeListVo.setFlowTypeName(String.valueOf(typeEnum.getName()));
            if(flowType <= 3){
                flowTypeInList.add(flowTypeListVo);
            }else if(flowType <= 8){
                flowTypeManageList.add(flowTypeListVo);
            }else if(flowType <= 14){
                flowTypeOutList.add(flowTypeListVo);
            }
        }
        flowTypeVo.setFlowTypeInList(flowTypeInList);
        flowTypeVo.setFlowTypeManageList(flowTypeManageList);
        flowTypeVo.setFlowTypeOutList(flowTypeOutList);
        return flowTypeVo;
    }

    public void pullDepartment(){
        List<GwyPullDepartmentListVo> departmentList = gwyCmsSystemService.pullDepartmentList();
        for (GwyPullDepartmentListVo departmentListVo : departmentList){
            String departmentNo = departmentListVo.getDepartmentNo();
            String parentDepartmentNo = departmentListVo.getParentDepartmentNo();
            String departmentName = departmentListVo.getDepartmentName();
            GwyDepartment department = departmentMapper.selectOne(new LambdaQueryWrapper<GwyDepartment>()
                    .eq(GwyDepartment::getDepartmentNo, departmentNo)
                    .last("limit 1"));
            if(department == null){
                GwyDepartment parentDepartment = departmentMapper.selectOne(new LambdaQueryWrapper<GwyDepartment>()
                        .eq(GwyDepartment::getDepartmentNo, parentDepartmentNo)
                        .last("limit 1"));
                GwyDepartment departmentInsert = new GwyDepartment();
                departmentInsert.setDepartmentName(departmentName);
                departmentInsert.setDepartmentNo(departmentNo);
                if(parentDepartment != null){
                    departmentInsert.setParentDepartmentId(parentDepartment.getDepartmentId());
                }
                departmentInsert.setDepartmentType(departmentListVo.getDepartmentType());
                departmentMapper.insert(departmentInsert);
            }else{
                department.setDepartmentName(departmentName);
                department.setDepartmentType(departmentListVo.getDepartmentType());
                GwyDepartment parentDepartment = departmentMapper.selectOne(new LambdaQueryWrapper<GwyDepartment>()
                        .eq(GwyDepartment::getDepartmentNo, parentDepartmentNo)
                        .last("limit 1"));
                if(parentDepartment != null){
                    department.setParentDepartmentId(parentDepartment.getDepartmentId());
                }
                departmentMapper.updateById(department);
            }
        }
    }
}
